<script setup lang="ts">
	import type { UploadProps } from 'element-plus'
	import { ElMessage, ElMessageBox } from 'element-plus'
	import axios from 'axios'
	import { ElLoading } from 'element-plus'
	import { getCurrentInstance, ref } from 'vue'
	import useUserStore from '@/store/modules/user'
	import { createDirectUploadTask, createMultipartUploadV2Task, FileData } from 'qiniu-js';
	import userApi from '@/api/modules/users/user.ts'
	// 自定义图片上传
	// function httpRequest(file: any) {

	//   // console.log(fd, file, '添加参数')
	//
	// }
	const percent : any = ref(false)
	const percentnum : any = ref(0)
	const loadicon = new URL('@/assets/images/loadicon.gif', import.meta.url).href
	const fullscreenLoading = ref(false)
	const props = withDefaults(
		defineProps<{
			action : UploadProps['action']
			// headers?: UploadProps['headers']
			headers ?: any
			data ?: UploadProps['data']
			name ?: UploadProps['name']
			url ?: string
			size ?: number
			width ?: number
			height ?: number
			placeholder ?: string
			notip ?: boolean
			ext ?: string[]
			dirname ?: string
			sizeT ?: string
			widtht ?: string
			heightt ?: string
			imgtype ?: string
			code ?: string
			isneedwh ?: boolean
		}>(),
		{
			name: 'file',
			dirname: 'picture', // 上传类型，picture-图片，banner-轮播
			url: '',
			size: 10,
			sizeT: 'MB', // 大小单位
			width: 150,
			height: 150,
			placeholder: '',
			notip: false,
			ext: () => ['jpg', 'png', 'gif', 'bmp'],
			action: `${import.meta.env.VITE_APP_API_BASEURL}Upload/QiniuUpload`,
			headers: {
				Authorization: `Bearer ${useUserStore().token}`,
			},
			widtht: '',
			heightt: '',
			imgtype: 'xx200', // 回显尺寸
			code: '', // 上传目录code
			isneedwh: false
		},
	)
	// 主目录：dirname-字段
	// adv（广告位模块）；
	// user（用户模块）：/user/merchant/（汽配商户），/user/member/（用户），/user/car/（汽修厂）
	// find（发现模块）；/find/trends/（动态），/find/memorabilia/（大事记），/find/business/（汽配商圈）
	// set（系统）；/set/vehiclemodel/（品牌），/set/carseries/（车系），/set/category/（类目），/set/agreement/（协议）

	// 引入自定义挂载公共方法
	const emits = defineEmits<{
		'update:url' : [
			url: string,
		]
		'onSuccess' : [
			res: any,
		]
	}>()
	const { pictureEcho, pictureType } = getCurrentInstance()!.appContext.config.globalProperties.$tools()
	// console.log(props.notip, '123333')
	defineOptions({
		name: 'ImageUpload',
	})

	const uploadData = ref({
		imageViewerVisible: false,
		progress: {
			preview: '',
			percent: 0,
		},
	})
	// 自定义上传
	async function httpRequest(file : any) {

		const token : any = await qiniu_token(file)
		qiniu_uploadFile(file, token)
		// if (pictureType(props.dirname) === false) {
		// 	ElMessage.error('未配置图片上传参数项')
		// 	return false
		// }
		// const fd = new FormData()
		// // fd.append('dirname', !props.code ? pictureType(props.dirname) : `${pictureType(props.dirname)}/${props.code}`)// 传参数
		// fd.append('file', file.file)// 传文件
		// // const loadingInstance = ElLoading.service({
		// // 	lock: true,
		// // 	text: 'Loading',
		// // 	background: 'rgba(0, 0, 0, 0.7)',
		// // })
		// fullscreenLoading.value = true
		// const res = await axios({
		// 	method: 'POST',
		// 	url: props.action,
		// 	data: fd,
		// 	headers: props.headers,
		// })
		// console.log('ImageUpload-单图', res.data)//
		// if (res.data.code === 0) {
		// 	fullscreenLoading.value = false
		// 	console.log(res.data, 'res.data')
		// 	emits('onSuccess', res.data)
		// } else {
		// 	fullscreenLoading.value = false
		// }
		// console.log(res.data.data, 自定义上传)//
	}
	function qiniu_uploadFile(file : any, token : any) {
		console.log(file, token, 'qiniu_uploadFile') //z这里拿的文件和token
		// const timestamp = Math.floor(Date.now() / 1000);
		// console.log(timestamp);
		// const fileData : FileData = { type: 'file', data: file.file, filename: file.name + ('1111') }
		const fileData : FileData = { type: 'file', data: file.file }
		let config = {
			useCdnDomain: true,
			region: 'z2', // 根据实际地区选择
			retryCount: 3, //上传自动重试次数  默认3次
			tokenProvider: () => {
				return Promise.resolve(token)
			},
		};
		// if (Math.floor(file.file.size / 1000000) > 0) {

		const uploadTask = createMultipartUploadV2Task(fileData, config);
		console.log(uploadTask, 'uploadTask 1')

		percent.value = true
		// 设置进度回调函数
		uploadTask.onProgress((progress : any, context : any) => {
			// 处理进度回调
			// console.log(progress, context, progress.percent, 'context123')
			percentnum.value = Math.round((((progress.percent * 100) - 75) * 4 || 0))
			console.log(progress, context, progress.percent, percentnum.value, 'context123')
		});

		// 设置完成回调函数
		uploadTask.onComplete((result : any, context : any) => {
			// 处理完成回调
			console.log(JSON.parse(result), context, '设置完成回调函数')
			percentnum.value = 100
			let newResult = JSON.parse(result)
			// if (!form.value.name) {
			// 	form.value.name = file.name
			// }
			// form.value.file = newResult.key
			console.log(newResult, 'newResultnewResult')
			emits('onSuccess', '/' + newResult.key)
			// console.log(form.value, 'that.form')
			setTimeout(() => {
				percent.value = false
				ElMessage.success(`资源上传成功`)
				percentnum.value = 0
			}, 500)
		});

		// 设置错误回调函数
		uploadTask.onError((error : any, context : any) => {
			percent.value = 0
			console.log(error, context, '设置错误回调函数')
			percent.value = false
			ElMessageBox.alert('文件上传失败，请联系管理员', '提示', {
				callback: (action : any) => { },
			})

		});

		uploadTask.start()
		// } else {
		// 	const uploadTask = createDirectUploadTask(fileData, config);
		// }
		// createMultipartUploadV2Task(fileData, config).start()
		// 	.then((result : any) => {
		// 		// 处理任务完成结果
		// 	})
		// 	.catch((error : any) => {
		// 		// 处理任务启动失败错误
		// 	});
	}

	// 获取7牛token
	function qiniu_token(file : any) {
		console.log(file)
		return new Promise((resolve : any, reject : any) => {
			userApi.getToken({
				ext: file.file.name.substring(file.file.name.lastIndexOf('.') + 1)
			}).then((res : any) => {
				console.log(res, 'resres')
				resolve(res.token)
			}).catch((err : any) => {
				ElMessageBox.alert('七牛token验证失败，请联系管理员', '提示', {
					callback: (action : any) => { },
				})
				reject(err)
			})
		});
	}
	function closeLoad() {
		fullscreenLoading.value = false
	}

	// 预览
	function preview() {
		uploadData.value.imageViewerVisible = true
	}
	// 关闭预览
	function previewClose() {
		uploadData.value.imageViewerVisible = false
	}
	// 移除
	function remove() {
		emits('update:url', '')
	}
	const beforeUpload : UploadProps['beforeUpload'] = (file) => {
		const fileName = file.name.split('.')
		const fileExt = fileName.at(-1) ?? ''
		const isTypeOk = props.ext.includes(fileExt)
		const isSizeOk = file.size / 1024 / 1024 < props.size
		if (!isTypeOk) {
			ElMessage.error(`上传图片只支持 ${props.ext.join(' / ')} 格式！`)
		}
		if (!isSizeOk) {
			ElMessage.error(`上传图片大小不能超过 ${props.size}${props.sizeT}！`)
		}
		if (isTypeOk && isSizeOk) {
			uploadData.value.progress.preview = URL.createObjectURL(file)
		}

		return isTypeOk && isSizeOk
	}
	const onProgress : UploadProps['onProgress'] = (file) => {
		// console.log(file, '路劲')
		uploadData.value.progress.percent = file.percent
	}
	const onSuccess : UploadProps['onSuccess'] = (res) => {
		uploadData.value.progress.preview = ''
		uploadData.value.progress.percent = 0
		if (res) {
			emits('onSuccess', res)
		}
	}
</script>

<template>
	<div class="upload-container">
		<el-upload :show-file-list="false" :headers="headers" :action="action" :data="data" :name="name"
			:before-upload="beforeUpload" :on-progress="onProgress" :on-success="onSuccess" :http-request="httpRequest"
			drag class="image-upload">
			<el-image v-if="url === ''" :src="url === '' ? placeholder : url"
				:style="`width:${width}px;height:${height}px;`" fit="fill">
				<template #error>
					<div class="image-slot"
						:style="`width:${widtht ? widtht : width}px;height:${heightt ? heightt : height}px;`">
						<svg-icon name="ep:plus" />
					</div>
				</template>
			</el-image>
			<div v-else class="image">
				<el-image :src="pictureEcho(url, imgtype)" :style="`width:${width}px;height:${height}px;`" fit="fill" />
				<div class="mask">
					<div class="actions">
						<span title="预览" @click.stop="preview">
							<svg-icon name="ep:zoom-in" />
						</span>
						<span title="移除" @click.stop="remove">
							<svg-icon name="ep:delete" />
						</span>
					</div>
				</div>
			</div>
			<div v-show="url === '' && uploadData.progress.percent" class="progress"
				:style="`width:${width}px;height:${height}px;`">
				<el-image :src="uploadData.progress.preview" :style="`width:${width}px;height:${height}px;`"
					fit="fill" />
				<el-progress type="circle" :width="Math.min(width, height) * 0.8"
					:percentage="uploadData.progress.percent" />
			</div>

		</el-upload>
		<div v-if="notip" class="el-upload__tip">
			<div style="display: inline-block;">
				<!-- 上传图片支持 ${ext.join(' / ')} 格式，且 -->
				<el-alert :title="`图片大小不超过${size} ${sizeT}，建议图片尺寸为${isneedwh?'16:9 或':''} ${width}:${height}`"
					type="info" show-icon :closable="false" />
			</div>
		</div>
		<el-image-viewer v-if="uploadData.imageViewerVisible" :url-list="pictureEcho([url], 'ss800')" teleported
			@close="previewClose" />
		<!-- 上传时的加载遮罩层 -->
		<!-- <div v-if="fullscreenLoading" class="loading-mask">
			<div class="flex justify-center items-center d-c ">
				<div class=" c-[#409eff]">
					<img class="w-5 h-5" :src="loadicon" alt>
				</div>
				<div class="my-4 c-[#409eff]">上传中...</div> 
				<div style="position: fixed; top:60px;right:60px; z-index:1000000;  border-radius: 50%; background-color: rgba(255, 255, 255, 0.8);"
					class="w-16 h-16 flex justify-center items-center font-size-10 cursor-pointer c-[#333]"
					@click="closeLoad">
					<svg-icon name="ep:close" />
				</div>
			</div>
		</div> -->
		<div v-if="percent" class="fixed demo-progress w-130 bg-[#fff]  top-50% left-50% "
			style="transform: translate(-50%,-50%); border-radius: 8px; box-shadow: 0px 0px 8px 0px #999; z-index:99999;">
			<!-- <div class="w-full text-end pr-4 pt-4 font-size-6 cursor-pointer" @click="closepercent">
				<svg-icon name="ep:close" />
			</div> -->
			<div class="w-full d-c flex justify-center items-center h-40  py-2 h-16" style=" ">
				<el-progress :width="500" striped striped-flow :text-inside="true" :stroke-width="24"
					:percentage="percentnum" status="success" />
				<div>
					<div class="my-4 c-[#67c23a]" v-if="percentnum>0">上传中...</div>
					<div class="my-4 c-[#e67c28]" v-else>正在解析文件流...</div>
				</div>
			</div>

		</div>

	</div>
</template>

<style lang="scss" scoped>
	.upload-container {
		line-height: initial;
	}

	.loading-mask {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		background-color: rgba(0, 0, 0, 0.7);
		display: flex;
		justify-content: center;
		align-items: center;
		z-index: 2000;
		/* 确保在el-loading之上 */
	}

	.el-loading {
		position: relative;
	}

	.demo-progress .el-progress--line {
		margin-bottom: 15px;
		width: 450px;
		height: 30px;
	}

	.el-loading .el-button {
		position: absolute;
		top: 10px;
		right: 10px;
	}

	.el-image {
		display: block;
	}

	.image {
		position: relative;
		border-radius: 6px;
		overflow: hidden;

		.mask {
			opacity: 0;
			position: absolute;
			top: 0;
			width: 100%;
			height: 100%;
			background-color: var(--el-overlay-color-lighter);
			transition: opacity 0.3s;

			.actions {
				width: 100px;
				height: 100px;
				display: flex;
				flex-wrap: wrap;
				align-items: center;
				justify-content: center;

				@include position-center(xy);

				span {
					width: 50%;
					text-align: center;
					cursor: pointer;
					color: var(--el-color-white);
					transition: color 0.1s, transform 0.1s;

					&:hover {
						transform: scale(1.5);
					}

					.icon {
						font-size: 24px;
					}
				}
			}
		}

		&:hover .mask {
			opacity: 1;
		}
	}

	.image-upload {
		display: inline-block;
		vertical-align: top;
	}

	:deep(.el-upload) {
		.el-upload-dragger {
			display: inline-block;
			padding: 0;

			&.is-dragover {
				border-width: 1px;
			}

			.image-slot {
				display: flex;
				justify-content: center;
				align-items: center;
				width: 100%;
				height: 100%;
				color: var(--el-text-color-placeholder);
				background-color: transparent;

				.icon {
					font-size: 30px;
				}
			}

			.progress {
				position: absolute;
				top: 0;

				&::after {
					content: "";
					position: absolute;
					width: 100%;
					height: 100%;
					left: 0;
					top: 0;
					background-color: var(--el-overlay-color-lighter);
				}

				.el-progress {
					z-index: 1;

					@include position-center(xy);

					.el-progress__text {
						color: var(--el-text-color-placeholder);
					}
				}
			}
		}
	}

	.cancel-loading {
		position: absolute;
		top: 62%;
		left: 50%;
		transform: translate(-50%, -50%);
		z-index: 9999;
		/* 确保 z-index 高于遮罩层 */
	}
</style>